package com.example.node.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.example.node.R;
import com.example.node.base.BaseActivity;

public class WebViewActivity extends BaseActivity {
    private WebView mWebView;
    private ProgressBar mProgressBar;
    private String title;
    private String url;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_webview);
        initView();
    }

    private void initView() {
        mWebView = findViewById(R.id.mWebView);
        mProgressBar = findViewById(R.id.mProgressBar);

        Intent intent = getIntent();
        title = intent.getStringExtra("title");
        url = intent.getStringExtra("url");
        if (!TextUtils.isEmpty(title)) {
            getSupportActionBar().setTitle(title);
        }
        if (!TextUtils.isEmpty(url)) {
            initWebView();
        }
    }

    private void initWebView() {
        WebSettings webSettings = mWebView.getSettings();
        //支持JS
        webSettings.setJavaScriptEnabled(true);
        //支持缩放
        webSettings.setSupportZoom(true);
        webSettings.setBuiltInZoomControls(true);
        //设置缓存
        webSettings.setAppCacheEnabled(true);

        //设置加载进度
        onWebChromeClient onWebChromeClient=new onWebChromeClient();
        mWebView.setWebChromeClient(onWebChromeClient);
        mWebView.loadUrl(url);

        //本地浏览
        mWebView.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                view.loadUrl(url);
                return true;
            }
        });
    }

    public class onWebChromeClient extends WebChromeClient{
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            if(newProgress==100){
                mProgressBar.setVisibility(View.GONE);
            }
        }
    }

/*    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_BACK&&mWebView.canGoBack()){
            mWebView.goBack();
        }
        return false;
    }*/

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //回收资源
        if (mWebView!=null){
            mWebView.destroy();
        }
    }
}
